package com.china08.yxyapi.api.manage.tec.teaching.lecture.teachreport;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.service.manage.tec.teaching.lecture.LectureReportClassImportService;

/**
 * 老师--导入授课报告
 * 
 * @author yaoguanglin
 *
 */
@CrossOrigin
@RestController
public class LectureReportClassImportPackUploadController extends YxyApiBaseController {

    @Autowired
    private LectureReportClassImportService lectureReportClassImportService;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/testreport/class/import/file", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(//
            @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {

        RespModel respModel = new RespModel();
        InputStream inputStream = null;
        Assert.isTrue((file != null), "文件找不到了");
        String name = file.getOriginalFilename();
        Assert.isTrue(StringUtils.isNotBlank(name), "文件名称为空");

        // 文件后缀
        String filePostfix = FilenameUtils.getExtension(name);
        Assert.isTrue(filePostfix.equals("yunxiao"), "文件类型错误");
        String encoding = "UTF-8";
        inputStream = file.getInputStream();
        byte[] filecontent = new byte[(int) file.getSize()];
        // 读取文件内容
        inputStream.read(filecontent);

        String data = new String(filecontent, encoding);
        // 解析数据并存入数据库
        lectureReportClassImportService.importFile(data);

        respModel.setMessage("导入成功");

        return respModel;
    }

    public static class ReqModel extends YxyApiReqModel {

    }

    protected static class RespModel extends YxyApiRespModel {
    }

}
